#import "SchoolWorkNoticeViewController.h"
#import "ScreenAdapter.h"
#import "CameraGalleryManager.h"
#import "UserDao.h"
#import <MobileCoreServices/UTCoreTypes.h>
#import "NetWorkManager.h"
#import "PopUIManager.h"
#import "JsonUtil.h"
#import "DynamicViewController.h"

#define PADDING 10

@interface SchoolWorkNoticeViewController ()

@end

@implementation SchoolWorkNoticeViewController
@synthesize titleInput,contentInput,scrollView,content_placeholder, addImage, buttonArrays, imageArrays,dynamicViewController;

- (void)viewDidLoad {
    [super viewDidLoad];
    
    contentInput.delegate = self;
    titleInput.delegate = self;
    
    selectedImageNums = 0;  //程序选中上传的图片数量，代表已经显示在待上传界面的数量
    imageArrays = [NSMutableArray arrayWithCapacity:9];
    buttonArrays = [[NSMutableArray alloc]init];
    
    ScreenAdapter* sa = [ScreenAdapter getInstanse];
    picW = (sa.screenWidth - 4 * PADDING) / 3.0;
    
    // Do any additional setup after loading the view from its nib.
    addImage = [[UIButton alloc]init];
    addImage.frame = CGRectMake(PADDING, 0, picW, picW);
    [addImage setBackgroundImage:[UIImage imageNamed:@"add_picture.png"] forState:UIControlStateNormal];
    [addImage addTarget:self action:@selector(addImageCallback:) forControlEvents:UIControlEventTouchUpInside];
    [scrollView addSubview:addImage];
    
    content_placeholder = [[UILabel alloc]init];
    content_placeholder.frame = CGRectMake(0, 6, contentInput.bounds.size.width, 20);
    content_placeholder.text = @"请输入内容";
    content_placeholder.textColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.1];
    content_placeholder.backgroundColor = [UIColor clearColor];
    content_placeholder.enabled = NO;
    content_placeholder.font = [UIFont fontWithName:@"Helvetica" size:14];

    [contentInput addSubview:content_placeholder];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if ((int)buttonIndex == 0L) {  //拍照
        //延时0.3s调用相机
        [self performSelector:@selector(showCamera) withObject:nil afterDelay:0.3];
    }else if ((int)buttonIndex == 1){//相册
        [self selectMultipleImage];
    }else if ((int)buttonIndex == 2){//取消
        NSLog(@"cancel");
    }
}

- (void)selectMultipleImage{
    // Create the image picker
    ELCImagePickerController *elcPicker = [[ELCImagePickerController alloc] initImagePicker];
    elcPicker.maximumImagesCount = (9 - selectedImageNums); //Set the maximum number of images to select
    
    elcPicker.returnsOriginalImage = NO; //Only return the fullScreenImage, not the fullResolutionImage
    elcPicker.returnsImage = YES; //Return UIimage if YES. If NO, only return asset location information
    
    elcPicker.onOrder = NO; //For multiple image selection, display and return selected order of images
    
    elcPicker.imagePickerDelegate = self;
    
    //Present modally
    [self presentViewController:elcPicker animated:YES completion:nil];
}

/**
 *callback of ELCImagePicker
 */
- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info
{
    [self dismissViewControllerAnimated:YES completion:nil];
    
    NSMutableArray *images = [NSMutableArray arrayWithCapacity:[info count]];
    
    for (NSDictionary *dict in info) {
        if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypePhoto){ //选择的是图片
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];  //将选取的图片放到images数组中
                //TODO 将多张图片显示到界面上。等待用户点击发送上传到服务器。
            } else {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        } else if ([dict objectForKey:UIImagePickerControllerMediaType] == ALAssetTypeVideo){ //选择的是视频
            if ([dict objectForKey:UIImagePickerControllerOriginalImage]){
                UIImage* image=[dict objectForKey:UIImagePickerControllerOriginalImage];
                [images addObject:image];
            } else {
                NSLog(@"UIImagePickerControllerReferenceURL = %@", dict);
            }
        } else {
            NSLog(@"Uknown asset type");
        }
    }
    [self showSelectedImageInView:images];
    
    NSLog(@"callback did finish pick.");
}

- (void) showSelectedImageInView:(NSMutableArray*) images{
    //计算下一张图片的位置
    int tempNums = selectedImageNums + 1;
    
    int current_row = tempNums / 3;
    int current_column = tempNums % 3;
    if (tempNums == 3) {
        current_column = 3;
        current_row = 0;
    }
    
    if (tempNums == 6) {
        current_column = 3;
        current_row = 1;
    }
    
    if (tempNums == 9) {
        current_column = 3;
        current_row = 2;
    }
    
    CGFloat maxY = 0;
    float close_button_width = picW / 4;
    for (UIImage* img in images) {
        [imageArrays addObject:img];
        
        float startX = (current_column - 1) * (picW+PADDING) + PADDING;
        float startY = current_row * (picW+PADDING);
        
        UIButton* button = [[UIButton alloc]init];
        [button setBackgroundImage:img forState:UIControlStateNormal];
        button.frame = CGRectMake(startX, startY, picW, picW);
        [scrollView addSubview:button];
        
        UIButton* deleteButton = [[UIButton alloc]init];
        UIImage *closeImg = [UIImage imageNamed:@"wechat.png"];
        [deleteButton setBackgroundImage:closeImg forState:UIControlStateNormal];
        deleteButton.frame = CGRectMake(startX+picW - close_button_width, startY, close_button_width, close_button_width);
        [deleteButton addTarget:self action:@selector(deleteImage:) forControlEvents:UIControlEventTouchUpInside];
        deleteButton.tag = tempNums;
        [scrollView addSubview:deleteButton];
        
        [buttonArrays addObject:button];
        [buttonArrays addObject:deleteButton];
        
        tempNums++;
        current_row = tempNums / 3;
        current_column = tempNums % 3;
        if (tempNums == 3) {
            current_column = 3;
            current_row = 0;
        }
        
        if (tempNums == 6) {
            current_column = 3;
            current_row = 1;
        }
        
        if (tempNums == 9) {
            current_column = 3;
            current_row = 2;
        }
        maxY = CGRectGetMaxY(button.frame);
    }
    if (tempNums < 10) {
        float startX = (current_column - 1) * (picW+PADDING) + PADDING;
        float startY = current_row * (picW+PADDING);
        addImage.frame = CGRectMake(startX, startY, picW, picW);
        maxY = CGRectGetMaxY(addImage.frame);
    }
    selectedImageNums += (int)images.count;
    [scrollView setContentSize:CGSizeMake(self.view.frame.size.width, maxY + PADDING)];
}

- (void)deleteImage:(id)sender{
    UIButton* button = (UIButton*)sender;
    [imageArrays removeObjectAtIndex:(button.tag - 1)];
    //将原来视图的所有控件都移除
    for (UIButton* btn in buttonArrays) {
        [btn removeFromSuperview];
    }
    //重新对所有的进行布局添加。
    selectedImageNums = 0;
    NSMutableArray *arr = [NSMutableArray arrayWithArray:imageArrays];
    [imageArrays removeAllObjects];
    [self showSelectedImageInView:arr];
    
}

- (void)elcImagePickerControllerDidCancel:(ELCImagePickerController *)picker
{
    NSLog(@"cancel select image.");
    [self dismissViewControllerAnimated:YES completion:nil];
}
//==================END====================

- (void) showCamera{
    [[CameraGalleryManager getInstanse] takePhoto:self finishBlock:^(UIImage *img, NSString * avaURL) {
        NSLog(@"Camera finish callback....");
    }];

}

- (void)addImageCallback:(id)sender{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"选取照片" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"相册",nil];
    [sheet showInView:self.view];
}

- (IBAction)sendNotice:(id)sender {
    NSString *title = titleInput.text;  //上传的标题
    NSString *content = contentInput.text;  //上传的内容
    //imageArrays; //待上传的图片
    
    int tp = 2;
    if (tp == 2 || tp == 3) {
        tp = 5 - tp;
    }
    NSString* utype = [NSString stringWithFormat:@"%d",tp];
    
    NSString *uid = [NSString stringWithFormat:@"%ld",[[UserDao getInstance] getUserId]];
    NSString *token = [[UserDao getInstance]getAccessToken];
    //园务通知的类型是1
    NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObjectsAndKeys: utype, @"utype",uid, @"uid",token, @"token", title, @"title", content, @"content", @"1", @"noticetype", @"SEND_NOTICE", @"message",nil];
    
    PopUIManager *popUIMgr = [PopUIManager getInstanse];
    [popUIMgr showWaitingUI:self.view];
    [[NetWorkManager getInstanse] uploadMultipleImageToServer:dict imageArray:imageArrays FinishBlock:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dict = [JsonUtil convertDataToDictionary:data];
        NSLog(@"finish> send dynamic...\n%@",dict);
        [popUIMgr removeWaitingUI];
        [dynamicViewController startHeaderRefresh];
        [self.navigationController popViewControllerAnimated:YES];
    }];
}


- (IBAction)backButton:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length == 0) {
        content_placeholder.text = @"请输入内容";
    }else{
        content_placeholder.text = @"";
    }
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField{
    [self.view endEditing:YES];
    return YES;
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if ([@"\n" isEqualToString:text] == YES)
    {
        [textView resignFirstResponder];
        return NO;
    }
    
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
